import { Doughnut } from 'react-chartjs-2'
import './setup' // 确保Chart.js组件被注册
import { commonOptions, colors } from './chartConfig'
import { getCategoryLabel } from '../../utils'

interface CategoryStats {
  category: string
  total: number
  completed: number
  pending: number
  completionRate: number
}

interface CategoryPieChartProps {
  data: CategoryStats[]
}

export default function CategoryPieChart({ data }: CategoryPieChartProps) {
  if (data.length === 0) {
    return (
      <div className="h-64 flex items-center justify-center text-theme-text-muted">
        <div className="text-center">
          <div className="w-16 h-16 bg-theme-bg-tertiary rounded-full flex items-center justify-center mx-auto mb-3">
            🥧
          </div>
          <p>暂无分类数据</p>
        </div>
      </div>
    )
  }

  const chartColors = [
    colors.primary.bg,
    colors.success.bg,
    colors.warning.bg,
    colors.error.bg,
    colors.purple.bg,
    colors.indigo.bg
  ]

  const chartData = {
    labels: data.map(item => getCategoryLabel(item.category)),
    datasets: [
      {
        data: data.map(item => item.total),
        backgroundColor: chartColors.slice(0, data.length),
        borderColor: chartColors.slice(0, data.length).map(color => 
          color.replace('0.8', '1').replace('rgba', 'rgb').replace(', 1)', ')')
        ),
        borderWidth: 2,
        hoverOffset: 8,
        hoverBorderWidth: 3
      }
    ]
  }

  const options = {
    ...commonOptions,
    plugins: {
      ...commonOptions.plugins,
      legend: {
        ...commonOptions.plugins?.legend,
        position: 'bottom' as const,
        labels: {
          ...commonOptions.plugins?.legend?.labels,
          padding: 15,
          generateLabels: (chart: any) => {
            const datasets = chart.data.datasets
            if (datasets.length) {
              const dataset = datasets[0]
              return chart.data.labels.map((label: string, i: number) => {
                const value = dataset.data[i]
                const total = dataset.data.reduce((a: number, b: number) => a + b, 0)
                const percentage = total > 0 ? Math.round((value / total) * 100) : 0
                
                return {
                  text: `${label} (${percentage}%)`,
                  fillStyle: dataset.backgroundColor[i],
                  strokeStyle: dataset.borderColor[i],
                  lineWidth: 2,
                  hidden: false,
                  index: i
                }
              })
            }
            return []
          }
        }
      },
      tooltip: {
        ...commonOptions.plugins?.tooltip,
        callbacks: {
          label: (context: any) => {
            const label = context.label || ''
            const value = context.parsed
            const total = context.dataset.data.reduce((a: number, b: number) => a + b, 0)
            const percentage = total > 0 ? Math.round((value / total) * 100) : 0
            return `${label}: ${value} 个任务 (${percentage}%)`
          }
        }
      }
    },
    cutout: '60%',
    radius: '90%',
    animation: {
      animateRotate: true,
      animateScale: true,
      duration: 1200,
      easing: 'easeOutQuart' as const
    }
  }

  return (
    <div className="h-64 relative">
      <Doughnut data={chartData} options={options} />
      {/* 中心显示总数 */}
      <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
        <div className="text-center">
          <div className="text-2xl font-bold text-theme-text">
            {data.reduce((sum, item) => sum + item.total, 0)}
          </div>
          <div className="text-xs text-theme-text-muted font-medium">总任务</div>
        </div>
      </div>
    </div>
  )
}
